
// Norm.ResultIterator.Jaxer.js
// Philip Weaver philip@philmaker.com

Norm.ResultIterator = function(resultSet, modelClass) {
	
	this.resultSet = resultSet;
	this.modelClass = modelClass;
	this.rowIndex = 0;
	this.first = true;
};

Norm.ResultIterator.prototype =  {
	
	next : function() {									// todo : add a function to retrive results as raw objects
		
		if (this.first) {
			this.first = false;
		} else {
			this.rowIndex++;
		}
		
		if (this.isValidRow()) {
			return new this.modelClass()._populateFromResult(this);
		} else {
			return this.close();
		}
	},
	
	each : function(fn, bind) {
		
		var current;
		while (current = this.next()) {
			fn.apply(bind || this, [current]);
		}
	},
	
	close : function() {
		
		//this.resultSet.close();
		return false;
	},
	
	getOne : function() {
		
		var instance = this.next();
		this.close();
		return instance;
	},
	
	toArray : function() {
		
		var arr = [];
		this.each(arr.push, arr);
		return arr;
	},
	
	isValidRow : function() {
		
		if ((this.resultSet) && (this.resultSet.rows) && (this.resultSet.rows.length > 0) && (this.rowIndex < this.resultSet.rows.length)) {
			return true;
		} else {
			return false;
		}
	},
	
	fieldByName : function(fieldName) {
		
		var index = this.resultSet.indexOfColumn(fieldName);
		return this.resultSet.rows[this.rowIndex].$values[index];
	}
	
};
